import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/counter_providers.dart';

/// Riverpod详情屏幕
/// 展示如何在不同屏幕间共享Riverpod状态
class RiverpodDetailScreen extends ConsumerWidget {
  const RiverpodDetailScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 监听计数器值用于AppBar显示
    final count = ref.watch(counterValueProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Riverpod Details'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          Center(
            child: Padding(
              padding: const EdgeInsets.only(right: 16.0),
              child: Text(
                '$count',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ],
      ),
      body: const Padding(
        padding: EdgeInsets.all(16.0),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _DetailedCounterInfo(),
              SizedBox(height: 16),
              _ProgressSection(),
              SizedBox(height: 16),
              _QuickActions(),
              SizedBox(height: 24), // 底部额外空间
            ],
          ),
        ),
      ),
    );
  }
}

/// 详细的计数器信息
class _DetailedCounterInfo extends ConsumerWidget {
  const _DetailedCounterInfo();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 监听多个状态
    final count = ref.watch(counterValueProvider);
    final status = ref.watch(statusProvider);
    final username = ref.watch(usernameProvider);
    final isEven = ref.watch(isEvenProvider);
    final nextMilestone = ref.watch(nextMilestoneProvider);

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Detailed Information',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            // 当前值
            _buildInfoRow(
              'Current Value',
              '$count',
              Icons.numbers,
              Colors.blue,
            ),

            // 状态
            _buildInfoRow(
              'Status',
              status,
              Icons.info_outline,
              _getStatusColor(status),
            ),

            // 用户
            _buildInfoRow('User', username, Icons.person_outline, Colors.green),

            // 是否为偶数
            _buildInfoRow(
              'Is Even',
              isEven ? 'Yes' : 'No',
              isEven ? Icons.check_circle : Icons.cancel,
              isEven ? Colors.green : Colors.red,
            ),

            // 距离下一个里程碑
            _buildInfoRow(
              'Next Milestone',
              nextMilestone,
              Icons.flag_outlined,
              Colors.orange,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String value, IconData icon, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Icon(icon, color: color, size: 24),
          const SizedBox(width: 12),
          Expanded(child: Text(label, style: const TextStyle(fontSize: 16))),
          Flexible(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: color,
              ),
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'Zero':
        return Colors.grey;
      case 'Low':
        return Colors.green;
      case 'Medium':
        return Colors.orange;
      case 'High':
        return Colors.red;
      default:
        return Colors.blue;
    }
  }
}

/// 进度显示区域
/// 展示如何使用计算属性
class _ProgressSection extends ConsumerWidget {
  const _ProgressSection();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 监听进度相关的计算属性
    final progressTo100 = ref.watch(progressTo100Provider);
    final progressTo500 = ref.watch(progressTo500Provider);
    final progressTo1000 = ref.watch(progressTo1000Provider);
    final count = ref.watch(counterValueProvider);

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Progress Statistics',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            _buildProgressSection('Progress to 100', count, 100, progressTo100),
            const SizedBox(height: 12),
            _buildProgressSection('Progress to 500', count, 500, progressTo500),
            const SizedBox(height: 12),
            _buildProgressSection(
              'Progress to 1000',
              count,
              1000,
              progressTo1000,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProgressSection(
    String title,
    int current,
    int target,
    double progress,
  ) {
    final percentage = (progress * 100).toInt();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              flex: 2,
              child: Text(title, style: const TextStyle(fontSize: 14)),
            ),
            Expanded(
              flex: 1,
              child: Text(
                '$current / $target ($percentage%)',
                textAlign: TextAlign.right,
                style: const TextStyle(fontSize: 12),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
        const SizedBox(height: 4),
        LinearProgressIndicator(
          value: progress,
          backgroundColor: Colors.grey[300],
          valueColor: AlwaysStoppedAnimation<Color>(
            progress == 1.0 ? Colors.green : Colors.blue,
          ),
        ),
      ],
    );
  }
}

/// 快速操作区域
class _QuickActions extends ConsumerWidget {
  const _QuickActions();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isLoading = ref.watch(isLoadingProvider);
    final count = ref.watch(counterValueProvider);

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Quick Actions',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            // 预设值按钮
            Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              children: [
                _buildPresetButton(context, ref, 'Set to 10', 10, count),
                _buildPresetButton(context, ref, 'Set to 25', 25, count),
                _buildPresetButton(context, ref, 'Set to 50', 50, count),
                _buildPresetButton(context, ref, 'Set to 100', 100, count),
              ],
            ),

            const SizedBox(height: 16),

            // 操作按钮
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: () {
                      ref.read(counterProvider.notifier).reset();
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('Counter reset to 0')),
                      );
                    },
                    icon: const Icon(Icons.refresh),
                    label: const Text('Reset'),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: isLoading
                        ? null
                        : () => ref
                              .read(counterProvider.notifier)
                              .incrementAsync(),
                    icon: isLoading
                        ? const SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(strokeWidth: 2),
                          )
                        : const Icon(Icons.cloud_upload),
                    label: Text(isLoading ? 'Loading...' : 'Async +1'),
                  ),
                ),
              ],
            ),

            const SizedBox(height: 12),

            // 随机操作
            SizedBox(
              width: double.infinity,
              child: OutlinedButton.icon(
                onPressed: () {
                  // 随机增加1-20之间的值
                  final randomValue =
                      (DateTime.now().millisecondsSinceEpoch % 20) + 1;
                  ref.read(counterProvider.notifier).addMultiple(randomValue);
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Added $randomValue randomly!')),
                  );
                },
                icon: const Icon(Icons.casino),
                label: const Text('Random Add (1-20)'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPresetButton(
    BuildContext context,
    WidgetRef ref,
    String label,
    int value,
    int currentCount,
  ) {
    final isCurrentValue = currentCount == value;

    return OutlinedButton(
      onPressed: isCurrentValue
          ? null
          : () {
              ref.read(counterProvider.notifier).setCount(value);
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(SnackBar(content: Text('Counter set to $value')));
            },
      style: OutlinedButton.styleFrom(
        backgroundColor: isCurrentValue ? Colors.grey[200] : null,
      ),
      child: Text(label),
    );
  }
}
